package com.acdc.wechat.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.acdc.wechat.dto.WechatUserInfo;
import com.acdc.wechat.service.WechatService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.web.service.SysLoginService;
import com.acdc.wechat.dto.WechatAuthResponse;
import com.ruoyi.common.utils.SecurityUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class AuthController {

    @Autowired
    private WechatService wechatService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysLoginService loginService;

    /**
     * 通过code获取用户信息
     */
    @GetMapping("/userInfo")
    public AjaxResult getUserInfoByCode(@RequestParam String code) {
        try {
            // 调用微信服务获取用户信息，只调用一次API获取access_token和openId
            WechatAuthResponse authResponse = wechatService.getAuthInfoByCode(code);
            String accessToken = authResponse.getAccessToken();
            String openId = authResponse.getOpenId();
            WechatUserInfo wechatUserInfo = wechatService.getUserInfo(openId, accessToken);
            SysUser user = userService.selectUserByOpenId(wechatUserInfo.getOpenId());
            if (user == null) {
                user = new SysUser();
                // 取openId后4位作为用户名
                user.setUserName(wechatUserInfo.getNickname() + wechatUserInfo.getOpenId().substring(wechatUserInfo.getOpenId().length() - 4));
                user.setPassword(SecurityUtils.encryptPassword(wechatUserInfo.getOpenId()));
                user.setOpenId(wechatUserInfo.getOpenId());
                user.setStatus("0");
                user.setDelFlag("0");
                user.setAvatar(wechatUserInfo.getHeadImgUrl());
                user.setNickName(wechatUserInfo.getNickname());
                user.setCreateBy("wechat");
                user.setCreateTime(new Date());
                user.setUpdateBy("wechat");
                user.setUpdateTime(new Date());
                userService.insertUser(user);
            }
            return AjaxResult.success(wechatUserInfo);
        } catch (Exception e) {
            log.error("获取微信用户信息失败", e);
            return AjaxResult.error("获取用户信息失败: " + e.getMessage());
        }
    }

    @PostMapping("/login")
    public AjaxResult wechatLogin(@RequestBody WechatUserInfo userInfo) {
        try {
            log.info("微信登录请求，用户信息: {}", userInfo);
            SysUser user = userService.selectUserByOpenId(userInfo.getOpenId());
            if (user == null) {
                log.error("用户不存在，openId: {}", userInfo.getOpenId());
                return AjaxResult.error("用户不存在");
            }
            log.info("找到用户: {}", user.getUserName());
            
            String token = loginService.login(user.getUserName(), user.getOpenId());
            log.info("登录成功，生成token: {}", token);
            
            // 构建返回数据
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            log.info("返回登录结果: {}", ajax);
            return ajax;
        } catch (Exception e) {
            log.error("微信登录失败", e);
            return AjaxResult.error("登录失败: " + e.getMessage());
        }
    }
}
